import React,{ PureComponent} from 'react'
import {connect} from 'react-redux'
import Topic from './components/Topic'
import List from './components/List'
import Writer from './components/Writer'
import Recommend from './components/Recommend'
import * as actionCreator from './store/actionCreator'
import { 
    HomeWrap,
    HomeLeft,
    Homeright,
    BackTop
} from './style'

class Home extends PureComponent{
    handleScrollTop(){
        window.screenTop(0, 0)
    }
    render(){
        return (
            <HomeWrap>
                <HomeLeft>
                    <img className="banner-img" src="//upload.jianshu.io/admin_banners/web_images/4401/0d3979171ba2937378a32495d6fd995d8820b05b.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540" alt="540" />
                    <Topic />
                    <List />
                </HomeLeft>
                <Homeright>
                    <Recommend/>
                    <Writer/>
                </Homeright>
                {this.props.showScroll ? <BackTop onClick={this.handleScrollTop}>顶部</BackTop> : null}
                
            </HomeWrap>
        )
    }
    componentDidMount(){
        this.props.changeHomeData();
        this.bindEvents();
    }
    componentWillUnmount(){
        
        window.removeEventListener('scroll',this.fn)
    }
    bindEvents(){
        this.fn = this.props.changeScrollTopshow(this.props.judge)
        window.addEventListener('scroll', this.fn)
    }
}
const mapState = (state) => ({
    showScroll: state.getIn(['home', 'showScroll'])
})


const mapDispatch = (dispatch) => ({
    changeHomeData(){
        const action = actionCreator.getHomeInfo()
        dispatch(action)
    },
    judge(){
        if(document.documentElement.scrollTop> 200){
            dispatch(actionCreator.toggleTopShow(true))
        }else{
            dispatch(actionCreator.toggleTopShow(false))
        }
    },
    changeScrollTopshow(fn, interval){
        let fisrt = true,
            timer = null,
            _self = fn;
        return ()=>{
            console.log('定时器')
            let args = arguments,
                _me = this;
            if(fisrt){
                _self.apply(_me, args)
                return fisrt = false
            }
            if(timer){
                return false
            }
            timer = setTimeout(()=> {
                clearTimeout(timer)
                timer = null
                _self.apply(_me, args)
            }, interval || 500)
        }
    }
})

export default connect(mapState, mapDispatch)(Home) 